
import __config from '@/config/env'; // 配置文件
import service from '@/store/service'; //存储相关数据服务util
const debug = true; //是否启用 debug 模式，true启用
const scope = 'server'; //登录时使用

const request = (url, method, data, showLoading) => {
	let access_token = getApp().globalData.access_token;
	let expires_in = getApp().globalData.expires_in; //过期时间
	console.log(__config.basePath + url,77777);
	let _url = __config.basePath + url;
	return new Promise((resolve, reject) => {
		if (!access_token) { //没有跳转登录
			service.removeRefreshToken();
			// uni.showToast({
			// 	icon: 'none',
			// 	position: 'bottom',
			// 	title: '身份验证信息已失效,请重新登录'
			// });
			uni.reLaunch({
				url: '/pages/login/login'
			});
			reject();
			return;
		}
		const curDateTime = new Date().getTime() + 120*1000; // 当前时间提前2分钟验证token过期时间
		if (curDateTime > expires_in) { // 如果当前时间大于token过期时间表示token已过期需要重新刷新token
			// token过期，刷新token
			refreshToken().then(response => {
				access_token = response.access_token;
			}).catch(response => {
				//失败 重新登录
				uni.hideLoading();
				reject();
				return;
			});
		}
		if (showLoading) {
			uni.showLoading({
				title: '加载中'
			});
		}
		console.log(url);
		uni.request({
			url: _url,
			method: method,
			data: data,
			withCredentials: true,
			header: {
				'Authorization': 'Bearer ' + access_token,
				'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
			},
			success(res) {
				uni.hideLoading();
				if (res.statusCode == 200) {
					if (res.data.code != 0) {
						if (res.data.code == 60001) {
							// session过期，则清除过期session，并重新加载
							// token过期，刷新token
							refreshToken().then(response => {
								uni.showModal({
									title: '提示',
									content: '出了点小差错，请重试一下～',
									success() {},
									complete() {}
								});
								reject("session过期");
							}).catch(response => {
								//失败 重新登录
								reject("session过期请重新登录");
								return;
							});
						} else if (res.data.code == 20001) {
							//兼容getui返回
							resolve(res.data);
						} else if (res.data.errCode != 0) {
							let errMsg = res.data.msg || res.errMsg
							uni.showModal({
								title: '提示',
								content: res.data.msg + '',
								success() {},
								complete() {}
							});
							reject(res.data.msg);
						} else { //兼容im返回
							resolve(res.data);
						}
					}
					resolve(res.data);
				} else if (res.statusCode == 401 || res.statusCode == 426) {
					service.removeUser();
					// 跳转到登录
					uni.reLaunch({
						url: '/pages/login/login'
					});
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: response.msg
					});
				} else if (res.statusCode == 404) {
					uni.showModal({
						title: '提示',
						content: '接口请求出错，请检查手机网络',
						success(res) {}
					});
					reject();
				} else {
					console.log(res,url);
					uni.showModal({
						title: '提示',
						content: res.data.msg + '',
						success(res) {}
					});
					reject();
				}
			},
			fail(error) {
				console.log("error");
				uni.hideLoading();
				if (error.errMsg && error.errMsg.indexOf('statusCode:-1') != -1) {
					console.log("无网络");
				} else {
					uni.showModal({
						title: '提示',
						content: '接口请求出错：' + error.errMsg,
						success(res) {}
					});
				}
				reject(error);
			},
			complete(res) {
				uni.hideLoading();
			}
		});
	});
};

// 不需要验证的接口，如登录时的接口
const requestNotValidate = (url, method, data, showLoading) => {
	let _url = __config.basePath + url;
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading({
				title: '加载中'
			});
		}
		uni.request({
			url: _url,
			method: method,
			data: data,
			withCredentials: true,
			header: {
				isToken: false,
				'Authorization': 'Basic YWRtaW46YWRtaW4=',
				'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
			},
			success(res) {
				uni.hideLoading();
				if (res.statusCode == 200) {
					resolve(res.data);
				} else if (res.statusCode == 404) {
					uni.showModal({
						title: '提示',
						content: '接口请求出错，请检查手机网络',
						success(res) {}
					});
					reject();
				} else if (res.statusCode == 401 || res.statusCode == 426) {
					service.removeUser();
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
					});
					reject(res.data);
				} else {
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						success(res) {}
					});
					reject();
				}
			},
			fail(error) {
				console.log(error);
				uni.hideLoading();
				uni.showModal({
					title: '提示',
					content: '接口请求出错：' + error.errMsg,
					success(res) {}
				});
				reject(error);
			},
			complete(res) {
				uni.hideLoading();
			}
		});
	});
};

// 刷新token
const refreshToken = () => {
	// token过期，刷新token
	const refresh_token = service.getRefreshToken();
	const grant_type = 'refresh_token';
	const query = '?refresh_token=' + refresh_token +
		'&grant_type=' + grant_type +
		'&scope=' + scope;
	return new Promise((resolve, reject) => {
		requestNotValidate('/auth/oauth/token' + query, 'POST', null, false).then(response => {
			// 登录成功 保存登录数据、本次登录的token
			service.saveAccessToken(response);
			resolve(response);
		}).catch(response => {
			//失败 重新登录
			service.removeRefreshToken();
			uni.showToast({
				icon: 'none',
				position: 'bottom',
				title: '身份验证信息已失效,请重新登录'
			});
			uni.reLaunch({
				url: '/pages/login/login'
			});
			reject();
		});
	});
}

/**
 * 上传文件接口
 * @param {Object} filePath 本地文件路径
 * @param {Object} dir 上传保存的文件目录, 如头像保存的目录: headimg/
 * @param {Object} fileType 文件类型(没有明确规定) image/video/file
 */
function uploadFile(filePath, dir, fileType) {
	let access_token = getApp().globalData.access_token;
	// 上传文件
	let _url = '/upms/file/upload?fileType='+fileType+'&dir='+dir;
	//#ifndef H5
	_url = __config.basePath + _url;
	//#endif
	return new Promise((resolve, reject) => {
		if (!access_token) {
			//没有跳转登录
			service.removeRefreshToken();
			uni.reLaunch({
				url: "/pages/login/login",
			});
			reject();
			return;
		}
		uni.uploadFile({
			url: _url,
			filePath: filePath,
			name: 'file',
			formData: {
				fileType: fileType,
				dir: dir
			},
			header: {
				Authorization: "Bearer " + access_token,
				"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
			},
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == '200') {
					let link = JSON.parse(uploadFileRes.data).link;
					resolve(link)
				} else {
					uni.showModal({
						title: "提示",
						content: "上传失败" + uploadFileRes.data,
						success(res) {}
					});
					reject()
				}
			},
			fail: (err) => {
				console.log(err);
				reject()
			},
			complete: () => {
				uni.hideLoading();
			}
		});
	})
}
module.exports = {
	uploadFile,
	request: (obj) => {
		// obj : {  //obj对象传进来的数据格式
		// 	url: '/mall/orderitem/page',
		// 	method: 'get',
		// 	params: query,
		// 	data: obj
		// }
		let url = obj.url; // 拼接query参数
		if (obj.params) {
			if (obj.params instanceof Object) {
				let p = [];
				for (let key in obj.params) {
					let t = key + '=' + obj.params[key];
					p.push(t);
				}
				url = obj.url + '?' + p.join('&')
			} else {
				url = obj.url + obj.params;
			}
		}
		return request(url, obj.method.toUpperCase(), obj.data, obj.showLoading ? obj.showLoading : false);
	},
	requestValidate: request,
	requestNotValidate,
	login: { // 登录接口
		randomStr: __config.basePath + '/code?randomStr=', // 获取验证码
		loginByUsername: (user) => {
			const grant_type = 'password';
			const password = encodeURIComponent(user.password); // 密码需要编码
			const query = '?username=' + user.username +
				'&password=' + password +
				'&randomStr=' + user.randomStr +
				'&code=' + user.code +
				'&grant_type=' + grant_type +
				'&scope=' + scope;
			return requestNotValidate('/auth/oauth/token' + query, 'POST', null, true);
		},
		refreshToken: (refresh_token) => {
			const grant_type = 'refresh_token';
			const query = '?refresh_token=' + refresh_token +
				'&grant_type=' + grant_type +
				'&scope=' + scope;
			return requestNotValidate('/auth/oauth/token' + query, 'POST', null, false);
		},
		loginByPhone: (phone, code) => {
			const grant_type = 'sms_login';
			const query = '?phone=' + phone +
				'&code=' + code +
				'&grant_type=' + grant_type;
			return requestNotValidate('/auth/phone/token/sms' + query, 'POST', null, true);
		},
		loginByThirdParty: (type, code) => {
			return requestNotValidate('/auth/thirdparty/token', 'POST', {
				'thirdparty': type + '@' + code
			}, true);
		},
		sendCode: (data) => {
			const query = '?phone=' + data.phone +
				'&type=' + data.type + '&graphCode=' + data.graphCode;
			return requestNotValidate('/upms/phone/code' + query, 'PUT', data, true);
		},
	},
	getUserInfo: data => {
		return request('/upms/user/info', 'GET', data, false);
	},
	logout: data => {
		return request('/auth/token/logout', 'DELETE', data, true);
	},
	register: data => {
		return request('/upms/user/register', 'POST', data, true);
	},
	mall: {
		// 快递公司
		orderlogistics: data => {
			return request('/mall/logistics/list', 'GET', data, false);
		},
		imLogin: data => {
			//im 登录
			return request('/mall/im/login', 'POST', data, false);
		},
		imRegister: data => {
			//im 注册
			return request('/mall/im/register', 'POST', data, false);
		},
		getuiAliasBind: data => {
			//个推绑定别名
			return request('/mall/getui/alias/bind', 'POST', data, false);
		},
		getuiAliasGet: cid => {
			//根据cid查询别名
			return request('/mall/getui/alias/' + cid, 'GET', null, false);
		},
		
		lotteryrolloutmergerecordingPage: data => {
			return request('/iotteryadmin/lotteryrolloutmergerecording/page', 'GET', data, false);
		},
		
		
	}
}
